//
//  shareFriendViewController.m
//  SunXi
//
//  Created by dllo on 15/12/6.
//  Copyright © 2015年 大远. All rights reserved.
//

#import "shareFriendViewController.h"

@interface shareFriendViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic, strong) UITableView *tableView;
@property(nonatomic, strong) UIView *HeardView;
@property (nonatomic, strong)CoreDataManager *manager;

@end


@implementation shareFriendViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    SV.BC = [UIColor whiteColor];
    //创建HeardView
    self.manager = [CoreDataManager defaults];

    [self initMyTableView];
    

}
- (void)initMyTableView{
    self.tableView = ({
        UITableView *table = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT) style:UITableViewStylePlain];
        table.delegate = self;
        table.dataSource = self;
        table.tableHeaderView = self.HeardView;
        table.rowHeight = 50;
        table;
    });
    [SV addSubview:self.tableView];
    
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (![UserModel shareSingleton].userFirend) {
        //同步请求好友列表
        [ShowMytext showHUDloadView:SV text:@"好友列表加载中..."];
        EMError *error = nil;
        NSArray *buddyList = [[EaseMob sharedInstance].chatManager fetchBuddyListWithError:&error];
        [ShowMytext hiddHUDloadView];
        if (!error) {
            [UserModel shareSingleton].userFirend = buddyList;
            [self.tableView reloadData];
        }else{
            [ShowMytext showAlertViewTitlt:@"错误" message:@"好友列表请求失败请重试" selector:self Block:^{
            }];
        }
    }else{
        [[EaseMob sharedInstance].chatManager asyncFetchBuddyListWithCompletion:^(NSArray *buddyList, EMError *error) {
            if (!error) {
                [UserModel shareSingleton].userFirend = buddyList;
                [self.tableView reloadData];
                [ShowMytext showHUDTextWithTitle:@"好友列表刷新完毕" View:SV];
            }
        } onQueue:nil];
    }
   
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [UserModel shareSingleton].userFirend.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MyfriendTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"myfriendCelll"];
    if (!cell) {
        cell = [[MyfriendTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"myfriendCelll"];
    }
    EMBuddy *buddy = [[UserModel shareSingleton].userFirend objectAtIndex:indexPath.row];
    cell.username.text = buddy.username;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    EMBuddy *buddy = [[UserModel shareSingleton].userFirend objectAtIndex:indexPath.row];
    [self pushMess:buddy.username];
    
}
- (void)pushMess:(NSString *)username{
    NSString *shaStr;
    switch ([shareModel sharedInstance].type) {
        case Look: {
            shaStr = [NSString stringWithFormat:@"SXlook:%@网址%@",[shareModel sharedInstance].title,[shareModel sharedInstance].code];
            break;
        }
        case Music: {
            shaStr = [NSString stringWithFormat:@"SXradio:%@网址%@",[shareModel sharedInstance].title,[shareModel sharedInstance].code];

            break;
        }
        case Movie: {
            shaStr = [NSString stringWithFormat:@"SXmovie:%@网址%@",[shareModel sharedInstance].title,[shareModel sharedInstance].code];

            break;
        }
        default: {
            break;
        }
    }
    
    
    EMChatText *txtChat = [[EMChatText alloc] initWithText:shaStr];
    EMTextMessageBody *body = [[EMTextMessageBody alloc] initWithChatObject:txtChat];
    
//    // 生成message
    EMMessage *message = [[EMMessage alloc] initWithReceiver:username bodies:@[body]];
    message.messageType = eMessageTypeChat; // 设置为单聊消息
//
    EMError *error = nil;
//
    id <IChatManager> chatManager = [[EaseMob sharedInstance] chatManager];
    [chatManager sendMessage:message progress:nil error:&error];
    if (error) {
        UIAlertView * a = [[UIAlertView alloc] initWithTitle:@"error" message:@"发送失败" delegate:nil cancelButtonTitle:@"好" otherButtonTitles:nil, nil];
        [a show];
    }else{
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"UserMess" inManagedObjectContext:self.manager.managedObjectContext];
        UserMess *model = [[UserMess alloc]initWithEntity:entity insertIntoManagedObjectContext:self.manager.managedObjectContext];
//        //赋值
        model.type = @2;
        model.mess = shaStr;
        model.user = username;
        NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
        NSTimeInterval time =[dat timeIntervalSince1970]*1000;
        NSString *str = [NSString stringWithFormat:@"%.0f",time];
        NSInteger numtime = [str integerValue];
        model.time = [NSNumber numberWithInteger:numtime];
        model.look = @0;
        [self.manager saveContext];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"新消息" object:nil];
    }
    [self windowhidd];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
